<template>
  <div class="furniture-list">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="家具名称">
          <el-input v-model="searchForm.name" placeholder="请输入家具名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="searchForm.brand" placeholder="请选择品牌" clearable>
            <el-option
              v-for="item in brandOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>家具列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增家具
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column prop="name" label="家具名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="code" label="编号" width="120" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span class="price">¥ {{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="家具名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入家具名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-select v-model="formData.brand" placeholder="请选择品牌">
            <el-option
              v-for="item in brandOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="formData.stock"
            :min="0"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
        <el-form-item label="是否套餐">
          <el-switch
            v-model="formData.isPackage"
            @change="handlePackageChange"
          />
        </el-form-item>
        <template v-if="formData.isPackage">
          <el-form-item label="套餐名称" prop="packageName">
            <el-input v-model="formData.packageName" placeholder="请输入套餐名称" />
          </el-form-item>
          
          <el-form-item label="套餐描述" prop="packageDesc">
            <el-input
              v-model="formData.packageDesc"
              type="textarea"
              rows="3"
              placeholder="请输入套餐描述"
            />
          </el-form-item>
          
          <el-form-item label="原价" prop="originalPrice">
            <el-input-number
              v-model="formData.originalPrice"
              :precision="2"
              :step="0.1"
              :min="0"
            />
          </el-form-item>
          
          <el-form-item label="优惠价" prop="discountPrice">
            <el-input-number
              v-model="formData.discountPrice"
              :precision="2"
              :step="0.1"
              :min="0"
            />
          </el-form-item>
          
          <el-form-item label="优惠说明" prop="discountDesc">
            <el-input
              v-model="formData.discountDesc"
              placeholder="请输入优惠说明"
            />
          </el-form-item>
          
          <el-form-item label="套餐商品">
            <el-table :data="formData.packageItems" border>
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column prop="name" label="商品名称">
                <template #default="{ row, $index }">
                  <el-select
                    v-model="row.furnitureId"
                    filterable
                    placeholder="请选择商品"
                    @change="(val) => handleItemSelect(val, $index)"
                  >
                    <el-option
                      v-for="item in furnitureOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="specs" label="规格" width="120" />
              <el-table-column prop="price" label="单价" width="120">
                <template #default="{ row }">
                  ¥ {{ row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="120">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.quantity"
                    :min="1"
                    :precision="0"
                    @change="calculateTotal"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    link
                    type="danger"
                    @click="removePackageItem($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-footer">
              <el-button type="primary" link @click="addPackageItem">
                <el-icon><Plus /></el-icon>添加商品
              </el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  name: '',
  type: '',
  brand: ''
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单相关
const dialogVisible = ref(false)
const isAdd = ref(true)
const submitting = ref(false)
const formRef = ref<FormInstance>()

const formData = ref({
  id: '',
  name: '',
  code: '',
  type: '',
  brand: '',
  price: 0,
  stock: 0,
  status: 1,
  description: ''
})

const formRules = {
  name: [{ required: true, message: '请输入家具名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  brand: [{ required: true, message: '请选择品牌', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 选项数据
const typeOptions = [
  { value: '客厅家具', label: '客厅家具' },
  { value: '卧室家具', label: '卧室家具' },
  { value: '餐厅家具', label: '餐厅家具' },
  { value: '书房家具', label: '书房家具' }
]

const brandOptions = [
  { value: '品牌A', label: '品牌A' },
  { value: '品牌B', label: '品牌B' },
  { value: '品牌C', label: '品牌C' }
]

// 模拟表格数据
const tableData = ref([
  {
    id: '1',
    name: '现代简约沙发',
    code: 'SF001',
    type: '客厅家具',
    brand: '品牌A',
    price: 2999,
    stock: 50,
    status: 1,
    description: '现代简约风格沙发'
  },
  // 更多数据...
])

const dialogTitle = computed(() => (isAdd.value ? '新增家具' : '编辑家具'))

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',
    brand: ''
  }
  handleSearch()
}

const handleAdd = () => {
  isAdd.value = true
  dialogVisible.value = true
  formData.value = {
    id: '',
    name: '',
    code: '',
    type: '',
    brand: '',
    price: 0,
    stock: 0,
    status: 1,
    description: ''
  }
}

const handleEdit = (row: any) => {
  isAdd.value = false
  dialogVisible.value = true
  formData.value = { ...row }
}

const handleDetail = (row: any) => {
  // 实现查看详情逻辑
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该家具吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      ElMessage.success('删除成功')
      loadData()
    })
    .catch(() => {})
}

const handleStatusChange = async (row: any) => {
  try {
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    console.error('更新状态失败：', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        ElMessage.success(`${isAdd.value ? '新增' : '编辑'}成功`)
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('保存失败：', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.furniture-list {
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .price {
      color: #f56c6c;
      font-weight: bold;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .furniture-list {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
  }
}
</style> 